package entity

import (
	"errors"
	"gorm.io/gorm"
	"log"
	"time"
)

type UserRepository struct {
	Id                 int       `json:"id"`
	Identity           string    `json:"identity"`
	UserIdentity       string    `json:"userIdentity"`
	ParentId           int       `json:"parentId"`
	RepositoryIdentity string    `json:"repositoryIdentity"`
	Type               string    `json:"type"`
	Name               string    `json:"name"`
	CreatedAt          time.Time `json:"createdAt" time_format:"2006-01-02 15:04:05"`
	UpdatedAt          time.Time `json:"updatedAt" time_format:"2006-01-02 15:04:05"`
	DeletedAt          time.Time `json:"-"`
}

func (*UserRepository) TableName() string {
	return "user_repository"
}
func (u *UserRepository) BeforeCreate(tx *gorm.DB) (err error) {
	// find father repo
	var cnt int64
	tx = tx.Model(&UserRepository{})
	err = tx.Where("user_identity= ? and parent_id=? and name=? and type=?", u.Identity, u.ParentId, u.Name, u.Type).Count(&cnt).Error
	if cnt > 0 {
		return errors.New("name exist")
	}

	if u.ParentId == 0 {
		return
	}

	err = tx.Where("user_identity= ? and id = ? and type != ?", u.Identity, u.ParentId, "dir").Count(&cnt).Error
	if cnt > 0 {
		return errors.New("parent repo must be a dir")
	}

	return
}
func (u *UserRepository) BeforeUpdate(tx *gorm.DB) (err error) {
	// find father repo
	var cnt int64
	tx = tx.Model(&UserRepository{})
	// first check name repeat
	err = tx.Where("user_identity=? and parent_id=? and name=? and type = ?", u.Identity, u.ParentId, u.Name, u.Type).Count(&cnt).Error
	if err != nil {
		log.Println(err)
		return err
	}
	if cnt > 0 {
		return errors.New("name exist")
	}
	if u.ParentId == 0 {
		return
	}
	// check uplevel is not dir?
	err = tx.Where("user_identity= ? and id = ? and type != ?", u.Identity, u.ParentId, "dir").Count(&cnt).Error
	if err != nil {
		log.Println(err)
		return err
	}
	if cnt > 0 {
		return errors.New("parent repo must be a dir")
	}
	return
}
